<template>
  <div class="app-container">
    <upload-excel :on-success="handleSuccess" :before-upload="beforeUpload" :href="href" />
    <el-table :data="tableData" border highlight-current-row style="width: 100%;margin-top:20px;">
      <el-table-column v-for="item of tableHeader" :key="item" :prop="item" :label="item" />
    </el-table>
  </div>
</template>

<script>
import { dateFormatExcel } from '@/utils'
import { importEmployee } from '@/api/employees'
export default {
  name: 'Import',
  data() {
    return {
      tableData: [],
      tableHeader: []
    }
  },
  computed: {
    type() {
      return this.$route.query.type
    },
    href() {
      if (this.type === 'employee') {
        return './excel/员工导入模板.xlsx'
      } else if (this.type === 'salarys') {
        return './excel/薪资导入模板.xlsx'
      } else {
        return ''
      }
    }
  },
  methods: {
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1
      if (isLt1M) {
        return true
      }
      this.$message({
        message: 'Please do not upload files larger than 1m in size.',
        type: 'warning'
      })
      return false
    },
    async handleSuccess({ results, header }) {
      // this.tableData = results
      // this.tableHeader = header
      if (this.type === 'employee') {
        this.import(results)
      }
    },
    async import(results) {
      console.log(results) // [{中文:值,中文值},{...,...}]
      const userRelations = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '聘用形式': 'formOfEmployment'
      }
      // 把 导入的数据 字段名字改为英文
      const arr = results.map(item => {
        const obj = {}
        Object.keys(userRelations).forEach(k => {
          if (k === '入职日期' || k === '转正日期') {
            obj[userRelations[k]] = dateFormatExcel(item[k])
          } else {
            obj[userRelations[k]] = item[k]
          }
        })
        return obj
      })

      // console.log(arr)
      await importEmployee(arr)
      this.$message.success('导入成功')
      this.$router.back()
    }
  }
}
</script>
